import BaseAnimation from "./BaseAnimation";

const { ccclass, property } = cc._decorator;

@ccclass
export default class AnimationComponent extends BaseAnimation {

    @property(cc.SpriteAtlas)
    atlas: cc.SpriteAtlas = null;

    setAtlas(atlas: cc.SpriteAtlas) {
        this.atlas = atlas;
    }

    start() {
        if (this.initFlag) {
            return;
        }
        this.init();
    }

    init() {
        this.initFlag = true;
        if (!this.animation) {
            this.node.addComponent(cc.Sprite)
            this.animation = this.node.addComponent(cc.Animation);
            if (this.animation && this.atlas) {
                this.animation.on('finished', this.onFinished, this);

                let frames = this.atlas.getSpriteFrames();
                let sf = frames[frames.length - 1];
                let rect = sf.getRect();
                this.node.setContentSize(rect.width, rect.height)
                var clip = cc.AnimationClip.createWithSpriteFrames(frames, 60);
                clip.name = this.actionName;
                this.animation.addClip(clip);
                // cc.log(' cocos animation init frames ',this.actionName,frames.length)
                if (this.autoPlay) {
                    this.play(this.actionName, this.count);
                }

            } else {
                cc.warn(' CocosAnimationComp is null ')
            }
        }


    }

    play(name: string, count: number = -1) {
        // cc.log(' cocos component paly ',count,name)
        this.setCount(count);
        let animState: cc.AnimationState = this.animation.play(this.actionName);
        if (this.count == -1) {
            animState.wrapMode = cc.WrapMode.Loop
            animState.repeatCount = Infinity;

        } else {
            animState.wrapMode = cc.WrapMode.Default;
            animState.repeatCount = this.count;
        }
    }

    onDestroy() {
        this.animation.off('finished', this.onFinished, this)
    }



    pause() {
        this.animation.pause();
    }

    resume() {
        this.animation.resume();
    }

    stop() {
        this.animation.stop();
    }
}
